﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;

namespace LingDingSoft
{
    public class SignatureCreater
    {
        private Dictionary<string, object> _params;
        private Parameter.RequestMetas _metas;
        private string _action;
        private string _token;
        private string _secret;
        public SignatureCreater(Dictionary<string, object> Params, Parameter.RequestMetas metas, string action, string token, string secret)
        {
            _action = action;
            _token = token;
            _secret = secret;
            _params = Params;
            _metas = metas;
        }
        public string GetResult()
        {
            StringBuilder rRts = new StringBuilder();
            string vRts = string.Empty;
            List<string> nl = new List<string>();
            if (_params != null)
            {
                foreach (var item in _params)
                {

                    nl.Add(string.Format("{0}={1}", item.Key, Newtonsoft.Json.JsonConvert.SerializeObject(item.Value)));
                }
            }

            nl.Add(string.Format("{0}=\"{1}\"", nameof(_metas.app_key), _metas.app_key));
            nl.Add(string.Format("{0}={1}", nameof(_metas.timestamp), _metas.timestamp));

            nl.Sort();
            foreach (var item in nl)
            {
                vRts += item;
            }
            vRts = _action + _token + vRts + _secret;

            MD5 md5 = new MD5CryptoServiceProvider();
            var vRtsMd5 = md5.ComputeHash(Encoding.UTF8.GetBytes(vRts));


            foreach (var item in vRtsMd5)
            {
                rRts.Append(item.ToString("X"));
            }

            return rRts.ToString();
        }
    }
}
